
#region using Statements

using System;
using System.Collections.Specialized;
using System.Configuration;

#endregion

namespace Windows.Live.SSO
{
    public static class WLID
    {

        #region GetWindowsLiveID

        public static string GetWindowsLiveID(string portalUser, string scenario)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            portalUser = RemoveDomain(portalUser);

            switch (scenario.ToUpper())
            {
                case "A": // AD = WLID
                case "1":
                    break;

                case "B": // XML Pair Attribute Lookup
                case "2":
                    XMLSearch searchXml = new XMLSearch(appSettings["dictionary"]);
                    portalUser = searchXml.GetWindowsLiveID(portalUser);
                    break;

                case "C": // AD Attribute Lookup (ADSI)
                case "3":
                    portalUser = ADSI.LookupWLID(portalUser, appSettings["WLIDattrName"]);
                    break;

                default:
                    throw new ApplicationException("Unknown scenario defined in the web.config.");
            }

            return AppendSuffix(portalUser);
        }
        #endregion

        #region RemoveDomain, AppendSuffix
        /// <summary>
        /// Retrieves and formats NTLM user name
        /// </summary>
        /// <param name="fullString"></param>
        /// <returns>user name of currently logged in</returns>
        public static string RemoveDomain(string userName)
        {
            userName = userName.Trim();
            if (userName.Contains("\\"))
            {
                userName = userName.Substring(userName.IndexOf("\\") + 1).Trim();
            }
            if (userName.Contains("/"))
            {
                userName = userName.Substring(userName.IndexOf("/") + 1).Trim();
            }

            return userName;
        }

        private static string AppendSuffix(string liveID)
        {
            if (liveID.Contains("@"))
            {
                return liveID;
            }

            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            if (Convert.ToBoolean(appSettings["suffixAppend"]))
            {
                liveID = RemoveDomain(liveID);
                return String.Format("{0}@{1}", liveID, appSettings["domain"]);
            }
            else
            {
                return liveID.Trim();
            }
        }
        #endregion
    }
}
